package com.study.config;

import com.alibaba.fastjson2.support.spring.data.redis.GenericFastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis启动类
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        // 创建RedisTemplate<String, Object>对象
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 配置连接工厂
        redisTemplate.setConnectionFactory(factory);
        // 设置键（key）的序列化方式为字符串序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        //下面的配置好像可以用这个代替
        //redisTemplate.setDefaultSerializer(new GenericFastJsonRedisSerializer());
        // 设置值（value）的序列化方式为我们自定义的Fastjson2序列化器

        //1 自定义的
        //redisTemplate.setValueSerializer(new Fastjson2RedisSerializer<>(Object.class)); // 这里使用泛型Object，可根据实际情况指定类型
        //2 直接使用的
        redisTemplate.setValueSerializer(new GenericFastJsonRedisSerializer());

        // 设置hash类型的key和value序列化方式
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        //redisTemplate.setHashValueSerializer(new Fastjson2RedisSerializer<>(Object.class));
        redisTemplate.setValueSerializer(new GenericFastJsonRedisSerializer());

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}
